package servlets;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.visualization.datasource.DataSourceServlet;
import com.google.visualization.datasource.base.DataSourceException;
import com.google.visualization.datasource.base.TypeMismatchException;
import com.google.visualization.datasource.datatable.ColumnDescription;
import com.google.visualization.datasource.datatable.DataTable;
import com.google.visualization.datasource.datatable.value.ValueType;
import com.google.visualization.datasource.query.Query;

import dataTypes.*;


@SuppressWarnings("serial")
public class StatServlet extends DataSourceServlet  {


	@Override
	public DataTable generateDataTable(Query arg0, HttpServletRequest arg1)
	throws DataSourceException {

		int bId = Integer.parseInt(arg1.getParameter("bId"));
		String action = arg1.getParameter("act");
		long dId = Integer.parseInt(arg1.getParameter("uId"));

		deal dl = null;
		List<deal> results=appManager.getInstance().getDealbyBusiness(bId);
		Key bKey=KeyFactory.createKey(business.class.getSimpleName(), bId);
		Key dKey=KeyFactory.createKey(bKey, deal.class.getSimpleName(), dId);


		if (action.equals("lastdeal") && results.size() != 0){
			
			for (deal d : results){
				if (d.getKey().equals(dKey))
					dl = d;
			}
			
			 int total = dl.getNumOfCoupons();
			 int purchased = dl.getNumPurchased();
			 int used = dl.getNumUsed();

			
			
			DataTable data = new DataTable();
			ArrayList<ColumnDescription> cd = new ArrayList<ColumnDescription>();
			cd.add(new ColumnDescription("name", ValueType.TEXT, "סוג"));
			cd.add(new ColumnDescription("link", ValueType.NUMBER, "כמות"));

			data.addColumns(cd);

			try {
				data.addRowFromValues("קופונים שנותרו", (total - purchased));
				data.addRowFromValues("קופונים שנרכשו ולא מומשו", (purchased - used));
				data.addRowFromValues("קופונים שנרכשו ומומשו", used);

			} catch (TypeMismatchException e) {
				System.out.println("Invalid type!");
			}
			return data;
		}
		
		else if (action.equals("lastdeal") && results.size() != 0){
			
		}
		return null;


	}
	
	 @Override
	  protected boolean isRestrictedAccessMode() {
	    return false;
	  }


}